<template>
	<div class="m-3">
		<n-collapse :expanded-names="1">
			<n-collapse-item title="基本设置" :name="1">
				<n-grid x-gap="12" :cols="3">
					<n-gi :span="1">
						<div class="flex justify-center cursor-pointer items-center flex-column">
							<img :src="avatarSrc" v-if="avatarSrc" alt="avatar" class="rounded-full h-35 w-35 flex items-center justify-center" @click="changeAvatar" />
							<n-avatar
								round
								v-else
								:style="{
									color: 'yellow',
									backgroundColor: backColor,
								}"
								class="h-35 w-35"
								@click="changeAvatar">
								{{ getUserName }}
							</n-avatar>
							<n-button class="m-t-7" @click="changeAvatar">更改头像</n-button>
						</div>
					</n-gi>
					<n-gi :span="1">
						<BasicForm ref="formRef" @register="register" labelAlign="left" layout="false" :showActionButtonGroup="false" />

						<n-button type="primary" @click="save"> 保存设置 </n-button>
					</n-gi>
				</n-grid>
			</n-collapse-item>
		</n-collapse>
	</div>
</template>

<script lang="ts" setup>
	import { useForm } from '@/components/Form';
	import { formSchema } from '@/views/system/personal/person.data';
	import { appThemeList } from '@/settings/designSetting';
	import { random } from 'lodash-es';
	import { upload } from '@/components/hUpload/upload-service';
	import commonUtil from '@/utils/common-util';
	const color = appThemeList;
	const backColor = color[random(color.length)];

	const $message = window['$message'];
	const [register, { getFieldsValue, validate, setFieldsValue }] = useForm({
		gridProps: { cols: 1, xGap: 120 },
		schemas: formSchema || [],
	});
	const formRef: any = ref(null);
	const { getUserInfo, getAvatar, getUserName } = useUserStore();
	let avatarSrc = ref(getAvatar);

	onMounted(() => {
		if (formRef) {
			setFieldsValue(getUserInfo);
		}
	});

	const changeAvatar = () => {
		upload().then(async (file) => {
			if (commonUtil.testFileName('.png/.jpeg', file[0])) {
				avatarSrc.value = URL.createObjectURL(file[0]);
			} else {
				$message.error('请上传图片');
			}
		});
	};
	const save = async () => {
		try {
			await validate();
			console.log(getFieldsValue());
			$message.success('保存成功');
		} catch (e) {
			console.log(e);
			$message.error('请输入完整信息');
		}
	};
</script>

<style scoped></style>
